package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.domain.PullDown;
import com.sale.system.domain.SysOfCode;
import com.sale.system.domain.SysOfInfo;
import com.sale.system.mapper.SysOfCodeMapper;
import com.sale.system.mapper.SysOfInfoMapper;
import com.sale.system.service.ISysOfCodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class SysOfCodeServiceImpl implements ISysOfCodeService {

    private final SysOfCodeMapper ofCodeMapper;

    private final SysOfInfoMapper ofInfoMapper;


    /**
     * 根据条件分页查询编码规则
     *
     * @param ofCode 编码规则
     * @return TableDataInfo
     */
    public TableDataInfo<SysOfCode> selectOfCodeList(SysOfCode ofCode,PageQuery pageQuery) {
        Page<SysOfCode> page = ofCodeMapper.selectOfCodeList(pageQuery.build(), this.buildQueryWrapper(ofCode));
        List<SysOfCode> list = page.getRecords();
        List<SysDictData> netArray = CacheUtils.get(CacheNames.SYS_DICT, "sys_ofcode_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        list.stream().forEach(sysOfCode -> sysOfCode.setOfCodeType(netMap.get(String.valueOf(sysOfCode.getOfCodeType()))));
        return TableDataInfo.build(page);
    }

    private Wrapper<SysOfCode> buildQueryWrapper(SysOfCode sysOfCode) {
        Map<String, Object> params = sysOfCode.getParams();
        QueryWrapper<SysOfCode> wrapper = Wrappers.query();
        wrapper
            .like(ObjectUtil.isNotNull(sysOfCode.getOfCodeStr()), "code_str", sysOfCode.getOfCodeStr())
            .like(StringUtils.isNotBlank(sysOfCode.getOfCodeName()), "code_name", sysOfCode.getOfCodeName())
            .eq(StringUtils.isNotBlank(sysOfCode.getOfCodeType()), "code_type", sysOfCode.getOfCodeType()).between(sysOfCode.getBeginTime() != null && sysOfCode.getEndTime() != null,
                "create_time", sysOfCode.getBeginTime(), sysOfCode.getEndTime());
        return wrapper;
    }



    /**
     * 编码新增
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int ofCodeAdd(SysOfCode ofCode) throws Exception {
       // ofCode.setCreateBy(SecurityUtils.getUsername());
        String kl = ofCode.getOp();
        int is = ofCodeMapper.selectOneOfCode(ofCode.getOfCodeStr());
        if(is>0){
            throw new SQLException("配置编码不能重复,请重新输入!");
        }
        List<SysOfInfo> list= JSONArray.parseArray(kl, SysOfInfo.class);
        int ids =  ofCodeMapper.ofCodeAdd(ofCode); //新增主表 返回主键ID
        int rows1 = 0;
        long idx = ofCode.getOfCodeId();
        if(ids>0){
            for (SysOfInfo sy :
            list) {
                sy.setCodeId(idx);
                rows1 = ofInfoMapper.ofCodeInfoAdd(sy);//更新从表
                if(rows1==0){
                    throw new SQLException("抛出异常");
                }
            }
        }
        return rows1;
    }

    /**
     * 删除编码
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOfCodeById(String ofCodeId) throws Exception {
        String[] idS = ofCodeId.split(",");
        int ui = ofCodeMapper.deleteOfCodeById(idS);
        int o=0;
        if(ui>0){
            o = ofInfoMapper.deleteInfoById(idS);
           if(o==0){
               throw new SQLException("抛出异常");
           }
        }
        return o;
    }

    /**
     * 修改编码
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOfEdit(SysOfCode ofCode) throws Exception {
        String kl = ofCode.getOp();
        List<SysOfInfo> list= JSONArray.parseArray(kl, SysOfInfo.class);
        int ui = ofCodeMapper.updateOfEdit(ofCode);
        long kp = ofCode.getOfCodeId();
        int rows2=0;
        if(ui>0){
            int c= ofInfoMapper.deleteInfoByIdS(kp);
            if(c>0){
                for (SysOfInfo sy :
                        list) {
                    sy.setCodeId(kp);
                    rows2 = ofInfoMapper.ofCodeInfoAdd(sy);//更新从表
                    if(rows2==0){
                        throw new Exception("抛出异常");
                    }
                }
            }else{
                throw new Exception("抛出异常");
            }
        }
        return rows2;
    }

    /**
     * 查询单个编码
     *
     * @return
     */
    @Override
    public SysOfCode selectOfCodeById(Long ofCodeId) {
        SysOfCode sysOfCodeS = ofCodeMapper.selectOfCode(ofCodeId);
        List<SysOfInfo> list2 = ofInfoMapper.selectOfInfoList(ofCodeId);
        sysOfCodeS.setInList(list2);
        return sysOfCodeS;


    }

    /**
     * 下拉
     *
     * @param
     * @return List<PullDown>
     */
    @Override
    public List<PullDown> selectOfCodeSelList() {
        return ofCodeMapper.selectOfCodeSelList();
    }

    /**
     * 获取页面数据(不带分页)
     *
     * @param
     * @return List<SysOfCode>
     */
    @Override
    public List<SysOfCode> selectOfCodeListBy() {
        return ofCodeMapper.selectOfCodeListBy();
    }

}
